-- HearthstoneToys_Main.lua
-- print("HearthstoneToys_Main.lua")

-- Declare the addon namespace
HearthstoneToys = {}
local addonName, addon = ...

-- Define a debug flag
addon.DEBUG = false  -- Set to true to enable debug prints

---------------
-- Constants --
---------------
addon.CONST = {
    ADDON_NAME = "HearthstoneToys",
    ADDON_DISPLAY_NAME = "炉石玩具",
    DB_NAME = "HearthstoneToysDB",
    ADDON_ICON_TEXTURE = "Interface\\Icons\\INV_Misc_Rune_01",
    TOY_FRAME_SHOW_SOUND_ID = 2022070,
    TOY_FRAME_HIDE_SOUND_ID = 2906065,
    ADDON_TEXT_COLOR = "|cFF00a7ff",
    DEBUG_TEXT_COLOR = "|cFFff0000",
    RESET_COLOR = "|r",
    mainFrame,
    toyButtons = {},
    availableToys = {},
    includeToys = {},
    presetNameInput,
    presetsDropdown,
    xPositionInput, yPositionInput,
    UpdateCooldown,
    optionsCategoryId,
    ADDON_VERSION = "1.11.7", -- Update this with each release
    ADDON_UPDATES = "避免了传送后出现“你已经学会”的垃圾信息，尤其是当你没有学会新玩具时。",
    WELCOME_MESSAGE = "输入'/hst'打开选项菜单。",
}

addon.isProfessionRequired = false
addon.requiredProfession = nil
addon.flavorTextOutputChannel = "private"
addon.requiresTargetForFlavor = false

-- Always track the GCD by spell ID
addon.COOLDOWN_SPELL_ID = 61304

-- Hearthstone shared item CD (keep this for Hearthstone Toys)
addon.COOLDOWN_ITEM_ID = 6948

--------------------------
-- List of toy item IDs --
--------------------------
addon.toyList = {
    {id = 54452, type = "toy"}, -- 虚灵之门
    {id = 64488, type = "toy"}, -- 旅店老板的女儿
    {id = 93672, type = "toy"}, -- 黑暗之门
    {id = 110560, type = "toy"}, -- 要塞炉石
    {id = 140192, type = "toy"}, -- 达拉然炉石
    {id = 142542, type = "toy"}, -- 城镇传送之书
    {id = 162973, type = "toy"}, -- 冬天爷爷的炉石
    {id = 163045, type = "toy"}, -- 无头骑士的炉石
    {id = 163206, type = "toy"}, -- Weary Spirit Binding
    {id = 165669, type = "toy"}, -- 春节长者的炉石
    {id = 165670, type = "toy"}, -- 小匹德菲特的可爱炉石
    {id = 165802, type = "toy"}, -- 复活节的炉石
    {id = 166746, type = "toy"}, -- 吞火者的炉石
    {id = 166747, type = "toy"}, -- 美酒节狂欢者的炉石
    {id = 168907, type = "toy"}, -- 全息数字化炉石
    {id = 172179, type = "toy"}, -- 永恒旅者的炉石
    {id = 180290, type = "toy"}, -- 法夜炉石
    {id = 182773, type = "toy"}, -- 通灵领主炉石
    {id = 183716, type = "toy"}, -- 温西尔罪碑
    {id = 184353, type = "toy"}, -- 格里恩炉石
    {id = 188952, type = "toy"}, -- 被统御的炉石
    {id = 190196, type = "toy"}, -- 开悟者炉石
    {id = 190237, type = "toy"}, -- 掮灵传送矩阵
    {id = 193588, type = "toy"}, -- 时光旅行者的炉石
    {id = 200630, type = "toy"}, -- 欧恩伊尔轻风贤者的炉石
    {id = 206195, type = "toy"}, -- 纳鲁之路
    {id = 208704, type = "toy"}, -- 幽邃住民的土灵炉石
    {id = 209035, type = "toy"}, -- 烈焰炉石
    {id = 210455, type = "toy"}, -- 德莱尼全息宝石
    {id = 212337, type = "toy"}, -- 炉之石
    {id = 228940, type = "toy"}, -- 恶名丝线炉石
    {id = 235016, type = "toy"}, -- 重部署模块
    {id = 236687, type = "toy"}, -- 高爆炉石	
    {id = 246565, type = "toy"}, -- 星瀚炉石
    {id = 245970, type = "toy"}, -- P.O.S.T.总管的特快炉石
    {id = 18984, type = "toy"}, -- 空间撕裂器：永望镇
    {id = 18986, type = "toy"}, -- 安全传送器：加基森
    {id = 30542, type = "toy"}, -- 空间撕裂器：52区
    {id = 30544, type = "toy"}, -- 超级安全传送器：托什雷的基地
    {id = 48933, type = "toy"}, -- 虫洞发生器：诺森德
    {id = 87215, type = "toy"}, -- 虫洞发生器：潘达利亚
    {id = 112059, type = "toy"}, -- 虫洞离心机
    {id = 151652, type = "toy"}, -- 虫洞发生器：阿古斯
    {id = 167075, type = "toy"}, -- 超级安全传送器：麦卡贡
    {id = 168807, type = "toy"}, -- 虫洞发生器：库尔提拉斯
    {id = 168808, type = "toy"}, -- 虫洞发生器：赞达拉
    {id = 172924, type = "toy"}, -- 虫洞发生器：暗影界
    {id = 198156, type = "toy"}, -- 龙洞发生器：巨龙群岛
    {id = 221966, type = "toy"}, -- 虫洞发生器：卡兹阿加
    {id = 6948, type = "item"}, -- 炉石
    {id = 37118, type = "item"}, -- 召回卷轴
    {id = 556, type = "spell"}, -- 星界传送
    {id = 44314, type = "item"}, -- 召回卷轴 II
    {id = 44315, type = "item"}, -- 召回卷轴 III	
}

--------------------
-- Flavor Message --
--------------------
addon.FLAVOR_MESSAGES = {
    "一位明智的法师曾说过：'火球术是最好的打招呼方式！'",
    "小心黑铁矮人。他们的酒比他们的盔甲还厉害！",
    "萨满祭司真正力量的秘密在于图腾敲击的声音！",
    "盗贼杀人并不需要理由，但通常是为了钱。",
    "猎人总是知道他们的猎物在哪里，特别是当他们饥饿的时候。",
    "牧师会治疗，但他们永远不会忘记你害死他们的时候！",
    "战士们热爱他们的战斗，但他们私下里渴望一顿美食。",
    "圣骑士总是做好准备。为了以防万一，他们会随身携带额外的祝福！",
    "法师们喜欢让他们的咒语保持炽热，而他们的双关语更是热火朝天！",
    "德鲁伊们热爱自然，但他们也不介意偶尔来点月光之火！",
    "德鲁伊与自然融为一体，但他们也无法抗拒一个温暖的熊抱！",
    "法师们会冻结他们的敌人，但他们的笑话才是真正的冷场之王！",
    "圣骑士们为每一种场合都准备了一把锤子...还有与之相配的光芒！",
    "战士们以剑为生...也可能死于更大的剑下。",
    "牧师们用神圣之怒痛击他们的敌人，但他们其实只是在为宾果之夜做练习。",
    "盗贼会消失，但你的钱包消失得更快！",
    "萨满召唤风暴，但他们是真正的自然之力！",
    "猎人的宠物很忠诚，但别让它们去捡东西！",
    "术士在底层总有朋友...比如在扭曲虚空里。",
    "术士不仅仅召唤恶魔；他们还能快速拨通恶魔的电话。",
    "当术士说'让我们做个约定吧'，最好仔细阅读一下小字部分。",
    "武僧们可能很禅定，但他们仍然能用一桶酒把你打晕！",
    "恶魔猎手拥有无与伦比的视野——只是别问他们是怎么失去深度知觉的。",
    "恶魔猎手不只是盯着你看；他们的凝视仿佛能穿透你的灵魂！",
    "恶魔猎手总是先跳后看...但通常都能成功！",
    "死亡骑士不需要心就能击碎你的心！",
    "侏儒可能很小，但他们的自尊心却恰到好处！",
    "矮人们相信，任何事物都可以用锤子来解决...甚至包括糟糕的笑话。",
    "兽人不需要咖啡——他们醒来时就已经准备好大干一场了。",
    "牛头人总是知道哪里的草更绿。找到它，就是他们的职责！",
    "血精灵已经完美掌握了在评判你时尚品味的同时保持自己风采的艺术。",
    "巨魔可能看起来很悠闲，但他们对猎头这件事可是非常认真的。",
    "人类是出色的外交家，这主要是因为他们在道歉方面有着丰富的实践经验。",
    "亡灵不需要睡美容觉，但不要对他们提这件事才是最礼貌的。",
    "地精相信'更多的爆炸'是解决任何问题的办法。",
    "对于地精来说，安全规定只是建议——而且还是昂贵的建议！",
    "即使过了几千年，暗夜精灵们仍然试图弄清楚为什么他们的头发会在夜晚发光。",
}

-- Saved variable to store settings
_G[addon.CONST.DB_NAME] = _G[addon.CONST.DB_NAME] or {}
_G[addon.CONST.DB_NAME].generalSettings = _G[addon.CONST.DB_NAME].generalSettings or {}
_G[addon.CONST.DB_NAME].mainFramePosition = _G[addon.CONST.DB_NAME].mainFramePosition or {}
_G[addon.CONST.DB_NAME].specificSettings = _G[addon.CONST.DB_NAME].specificSettings or {}
_G[addon.CONST.DB_NAME].toySettings = _G[addon.CONST.DB_NAME].toySettings or {}
_G[addon.CONST.DB_NAME].presets = _G[addon.CONST.DB_NAME].presets or {}

-- Default settings
addon.defaults = {
    generalSettings = {
        showWelcomeMessage = true,
        playSoundWhenFrameShown = true,
        lockPosition = false,
        version = addon.CONST.ADDON_VERSION,
    },
    mainFramePosition = {
        point = "CENTER",
        relativeTo = "UIParent",
        relativePoint = "CENTER",
        xOfs = 0,
        yOfs = 0,
    },
    specificSettings = {
        showChatMessage = true,
        showButtonOnMouseOver = false,
        toyFramePosition = "LEFT",
        buttonSize = 44,
    },
}

-- Initialize saved variables
function addon.InitializeAddon()
    if addon.DEBUG then
        addon.DebugPrint("addon.InitializeAddon called")
    end
    -- Initialize database using defaults
    for key, value in pairs(addon.defaults) do
        if type(value) == "table" then
            if not _G[addon.CONST.DB_NAME][key] then
                _G[addon.CONST.DB_NAME][key] = {}
            end
            for nestedKey, nestedValue in pairs(value) do
                if _G[addon.CONST.DB_NAME][key][nestedKey] == nil then
                    _G[addon.CONST.DB_NAME][key][nestedKey] = nestedValue
                end
            end
        else
            if _G[addon.CONST.DB_NAME][key] == nil then
                _G[addon.CONST.DB_NAME][key] = value
            end
        end
    end

    -- Set buttonSize to a local variable for easy access
    addon.buttonSize = _G[addon.CONST.DB_NAME].specificSettings.buttonSize

    -- Initialize toySettings with PlayerHasToy validation
    for _, toyListEntry in ipairs(addon.toyList) do
        local itemID = toyListEntry.id
        if type(itemID) == "number" and _G[addon.CONST.DB_NAME].toySettings[itemID] == nil then
            -- Default to true only if the player owns the toy
            _G[addon.CONST.DB_NAME].toySettings[itemID] = PlayerHasToy(itemID)
        end
    end

    -- Initialize components
    addon.UIFrames.Initialize()
    addon.OptionsPanel.Initialize()

    C_Timer.After(0.2, function()
        -- Register Slash Command
        SLASH_HST1 = "/hst"
        SlashCmdList["HST"] = function(msg)
            if addon.OptionsPanel.optionsCategoryId then
                -- Open the options panel using the registered category ID
                Settings.OpenToCategory(addon.OptionsPanel.optionsCategoryId)
            else
                print(addon.CONST.ADDON_TEXT_COLOR .. "[" .. addon.CONST.ADDON_DISPLAY_NAME .. "]: " .. addon.CONST.RESET_COLOR .. "选项面板尚未初始化。")
            end
        end
    end)
end

if addon.DEBUG then
    -- TEST COMMAND TO TEMPORARILY REMOVE A TOY FROM THE availableToys table
    SLASH_REMOVETOY1 = "/removetoy"
    SlashCmdList["REMOVETOY"] = function(msg)
        local testToyID = tonumber(msg)
        if not testToyID then
            print("使用：/removetoy <炉石ID>")
            return
        end

        local isValidToy = false
        for _, toy in ipairs(addon.toyList) do
            if toy.id == testToyID then
                isValidToy = true
                break
            end
        end

        if not isValidToy then
            print(addon.CONST.ADDON_TEXT_COLOR .. "[" .. addon.CONST.ADDON_DISPLAY_NAME .. "]: " .. addon.CONST.RESET_COLOR .. "无效的炉石ID。")
            return
        end

        -- Remove from toySettings
            _G[addon.CONST.DB_NAME].toySettings[testToyID] = nil
        addon.DebugPrint("炉石已从插件设置中删除：" .. testToyID)

        -- Fake that the player does NOT own it for this snapshot
        local originalPlayerHasToy = PlayerHasToy
        PlayerHasToy = function(id)
            if id == testToyID then
                return false
            else
                return originalPlayerHasToy(id)
            end
        end

        -- Rebuild snapshot with the toy marked as not owned
        addon.HandleNewToyAcquisition()

        -- Restore
        PlayerHasToy = originalPlayerHasToy
		
        addon.InitializeIncludedToys()
        addon.RefreshUI()
    end

    -- TEST COMMAND TO SIMULATE ACQUIRING A TOY
    SLASH_ACQUIRETOY1 = "/acquiretoy"
    SlashCmdList["ACQUIRETOY"] = function(msg)
        local testToyID = tonumber(msg) -- Parse the toy ID from the command
        if not testToyID then
            print("使用：/acquiretoy <toyID>")
            return
        end

        -- Validate that the toy exists in toyList
        local isValidToy = false
        for _, toy in ipairs(addon.toyList) do
            if toy.id == testToyID then
                isValidToy = true
                break
            end
        end

        if not isValidToy then
            print(addon.CONST.ADDON_TEXT_COLOR .. "[" .. addon.CONST.ADDON_DISPLAY_NAME .. "]: " .. addon.CONST.RESET_COLOR .. "无效的炉石ID。")
            return
        end

        -- Simulate PlayerHasToy behavior for the test
        local originalPlayerHasToy = PlayerHasToy -- Backup original function
		
        PlayerHasToy = function(id)
            if id == testToyID then
                return true -- Simulate that the toy is now owned
            else
                return originalPlayerHasToy(id)
            end
        end

        addon.DebugPrint("模拟增加新炉石ID：", testToyID)

        -- Trigger the normal acquisition handling process
        addon.HandleNewToyAcquisition()

        -- Restore original PlayerHasToy function
        PlayerHasToy = originalPlayerHasToy
    end
end